package physicsModeler;

import java.util.Vector;
import java.io.File;

import physicsModeler.objects.DrawObject;

public class ObjectFactory {

	String path; 
	
	Vector objNames;
	
	public ObjectFactory()
	{
		init(".\\bin\\physicsModeler\\objects\\");
	}
	
	public ObjectFactory(String path)
	{
		init(path);
		
	}
	
	public void init(String path)
	{
		Class c = null;
		Object o = null;
		String className = "";
		
		try{
		objNames = new Vector();
		File file = new File(path);
		
		String fileNames[] = file.list();
		
		for (int i = 0; i < fileNames.length; i++) { // Go through all files
            if (fileNames[i].endsWith(".class") == true) { // Ignore if not a Java .class file
                 if (fileNames[i].compareTo("DrawObject.class") != 0)
                 {
                	if (fileNames[i].compareTo("Sprite.class") != 0)
                	{ // Skip the DrawObject base class
                      // Try to load the class
                      try 
                      {
                           // Strip ".class" from the end
                           className = fileNames[i].substring(0, fileNames[i].length() - 6);

                           // Load the class and create an instance of it
                           c = Class.forName("physicsModeler.objects." + className);
                           o = c.newInstance();
                           if (o instanceof DrawObject) 
                           {
                                objNames.addElement(className);
                           }
                      } 
                      catch (Exception ex) 
                      {
                           ex.printStackTrace();
                      }
                	

                      // Verify that it is a DrawObject.  If so, add its class name to the
                      // shape list.
                      
                 }
                 }
            }
       }
		
		}// end try block
		catch(Exception ex)
		{
			ex.printStackTrace();
			
		}
		
	} // end init
	
	public Vector getShapeNames() {
	    return (Vector)objNames.clone();
	  }
	
	public DrawObject createDrawObject(String objectName) throws Exception {
	    try {
	      Class c = Class.forName("physicsModeler.objects." + objectName);
	      DrawObject d = (DrawObject)c.newInstance();
	      
	      return d;
	    }
	    catch (Exception ex) {
	      throw ex;
	    }
	  }
	
}
